package com.proyecto.track.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.proyecto.track.bo.UserPerson;
@Transactional

public class UserPersonDAOImp implements UserPersonDAO {

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Long createUserPerson(UserPerson userPerson) {
		sessionFactory.getCurrentSession().save(userPerson);
		return userPerson.getId();
	}

	@Override
	public Long deleteUserPerson(UserPerson userPerson) {
		Long id = userPerson.getId();
		sessionFactory.getCurrentSession().delete(userPerson);
		return id;
	}

	@Override
	public Long modifyUserPerson(UserPerson userPerson) {
		sessionFactory.getCurrentSession().update(userPerson);
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserPerson> searchUser() {

		return sessionFactory.getCurrentSession().createQuery("from UserPerson").list();
	}

	@Override
	public UserPerson searchUserPerson(Long id) {
		return (UserPerson) sessionFactory.getCurrentSession().get(UserPerson.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserPerson> searchUser(String text) {
		Query query = sessionFactory.getCurrentSession().createQuery("from UserPerson as up where up.name like :text or up.lastName like :text");
		query.setString("text", "%" + text + "%");
		return (List<UserPerson>)query.list();
	}
	
	public UserPerson searchUserPersonByAccount(Long idAccount) {
		System.out.println("ID QUE LLEGA "+idAccount);
		Query query = sessionFactory.getCurrentSession().createQuery("select up from UserPerson as up where up.account.id = :id");
		query.setParameter("id", idAccount);
		UserPerson u = (UserPerson) query.uniqueResult();
		return u;
	}

}
